<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<!-- 全局消息通知组件 -->
<div th:fragment="notification">
    <!-- 客服消息通知 -->
    <div id="customerServiceNotification" class="position-fixed" style="bottom: 20px; right: 20px; z-index: 9999; display: none;">
        <div class="card shadow-lg border-0" style="width: 350px; border-radius: 15px; overflow: hidden;">
            <div class="card-header bg-info text-white d-flex justify-content-between align-items-center" style="border-radius: 15px 15px 0 0;">
                <div class="d-flex align-items-center">
                    <i class="bi bi-headset me-2"></i>
                    <strong>客服消息</strong>
                </div>
                <button type="button" class="btn-close btn-close-white" onclick="closeNotification()"></button>
            </div>
            <div class="card-body p-3">
                <div class="d-flex align-items-start">
                    <div class="flex-shrink-0 me-3">
                        <div class="bg-info text-white rounded-circle d-flex align-items-center justify-content-center" 
                             style="width: 40px; height: 40px;">
                            <i class="bi bi-headset"></i>
                        </div>
                    </div>
                    <div class="flex-grow-1">
                        <h6 class="mb-1" id="notificationTitle">客服回复了您的消息</h6>
                        <p class="mb-2 text-muted small" id="notificationContent">您有新的客服回复，请查看</p>
                        <div class="d-flex gap-2">
                            <button class="btn btn-info btn-sm" onclick="goToCustomerService()">
                                <i class="bi bi-chat-left-text"></i> 查看消息
                            </button>
                            <button class="btn btn-outline-secondary btn-sm" onclick="closeNotification()">
                                稍后查看
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 全局消息检测脚本 -->
    <script>
        let globalNotificationInterval = null;
        let lastUnreadCount = 0;
        let notificationShown = false;
        
        // 页面加载完成后开始检测
        document.addEventListener('DOMContentLoaded', function() {
            // 检查用户角色，只有customer角色才启用通知
            checkUserRoleAndStartNotification();
        });
        
        // 页面离开时停止检测
        window.addEventListener('beforeunload', function() {
            stopGlobalNotification();
        });
        
        function checkUserRoleAndStartNotification() {
            // 通过检查页面中的用户角色信息来判断是否启用通知
            const userRoleElement = document.querySelector('[data-user-role]');
            const userRole = userRoleElement ? userRoleElement.getAttribute('data-user-role') : null;
            
            // 通过URL路径判断
            const currentPath = window.location.pathname;
            const isCustomerPage = currentPath.startsWith('/customer') || currentPath === '/' || currentPath === '/home';
            const isNotCustomerServicePage = !currentPath.includes('/customer-service');
            const isNotAdminPage = !currentPath.includes('/admin');
            
            // 只有customer角色且不在客服页面和管理页面时才启用通知
            if ((userRole === 'customer' || isCustomerPage) && isNotCustomerServicePage && isNotAdminPage) {
                console.log('启用全局客服消息通知');
                startGlobalNotification();
            } else {
                console.log('当前页面不需要客服消息通知:', currentPath, 'userRole:', userRole);
            }
        }
        
        function startGlobalNotification() {
            // 每5秒检查一次未读消息
            globalNotificationInterval = setInterval(function() {
                checkUnreadMessages();
            }, 5000);
            
            // 立即检查一次
            checkUnreadMessages();
        }
        
        function stopGlobalNotification() {
            if (globalNotificationInterval) {
                clearInterval(globalNotificationInterval);
                globalNotificationInterval = null;
            }
        }
        
        function checkUnreadMessages() {
            fetch('/customer/notifications')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const currentUnreadCount = data.unreadCount || 0;
                        const notifications = data.notifications || [];
                        
                        // 如果有新的未读消息且当前不在客服聊天页面
                        if (currentUnreadCount > lastUnreadCount && currentUnreadCount > 0) {
                            const currentPath = window.location.pathname;
                            const isNotInCustomerServiceChatPage = !currentPath.includes('/customer/customer-service');
                            
                            if (isNotInCustomerServiceChatPage && !notificationShown) {
                                console.log('检测到新的客服回复，显示全局通知');
                                // 获取最新的通知内容
                                const latestNotification = notifications[0];
                                if (latestNotification) {
                                    showCustomerServiceNotificationWithContent(currentUnreadCount, latestNotification);
                                } else {
                                    showCustomerServiceNotification(currentUnreadCount);
                                }
                            } else {
                                console.log('当前在客服聊天页面，不显示全局通知');
                            }
                        }
                        
                        lastUnreadCount = currentUnreadCount;
                        
                        // 如果没有未读消息，隐藏通知
                        if (currentUnreadCount === 0) {
                            hideNotification();
                        }
                    }
                })
                .catch(error => {
                    console.error('检查未读消息失败:', error);
                });
        }
        
        function showCustomerServiceNotificationWithContent(unreadCount, notification) {
            const notificationElement = document.getElementById('customerServiceNotification');
            const title = document.getElementById('notificationTitle');
            const content = document.getElementById('notificationContent');
            
            if (notificationElement && title && content) {
                title.textContent = `${notification.senderName} 回复了您的消息`;
                content.textContent = notification.messageContent || `您有 ${unreadCount} 条新的客服回复，请及时查看`;
                
                notificationElement.style.display = 'block';
                notificationElement.classList.add('animate__animated', 'animate__slideInRight');
                
                notificationShown = true;
                
                // 播放通知音效（可选）
                playNotificationSound();
                
                // 10秒后自动隐藏
                setTimeout(() => {
                    if (notificationShown) {
                        hideNotification();
                    }
                }, 10000);
            }
        }
        
        function showCustomerServiceNotification(unreadCount) {
            const notification = document.getElementById('customerServiceNotification');
            const title = document.getElementById('notificationTitle');
            const content = document.getElementById('notificationContent');
            
            if (notification && title && content) {
                title.textContent = '客服回复了您的消息';
                content.textContent = `您有 ${unreadCount} 条新的客服回复，请及时查看`;
                
                notification.style.display = 'block';
                notification.classList.add('animate__animated', 'animate__slideInRight');
                
                notificationShown = true;
                
                // 播放通知音效（可选）
                playNotificationSound();
                
                // 10秒后自动隐藏
                setTimeout(() => {
                    if (notificationShown) {
                        hideNotification();
                    }
                }, 10000);
            }
        }
        
        function hideNotification() {
            const notification = document.getElementById('customerServiceNotification');
            if (notification) {
                notification.style.display = 'none';
                notification.classList.remove('animate__animated', 'animate__slideInRight');
                notificationShown = false;
            }
        }
        
        function closeNotification() {
            hideNotification();
        }
        
        function goToCustomerService() {
            window.location.href = '/customer/customer-service';
        }
        
        function playNotificationSound() {
            // 创建简单的通知音效
            try {
                const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                const oscillator = audioContext.createOscillator();
                const gainNode = audioContext.createGain();
                
                oscillator.connect(gainNode);
                gainNode.connect(audioContext.destination);
                
                oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
                oscillator.frequency.setValueAtTime(600, audioContext.currentTime + 0.1);
                
                gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
                gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3);
                
                oscillator.start(audioContext.currentTime);
                oscillator.stop(audioContext.currentTime + 0.3);
            } catch (error) {
                console.log('无法播放通知音效:', error);
            }
        }
        
        // 暴露全局函数供其他页面使用
        window.globalNotification = {
            start: startGlobalNotification,
            stop: stopGlobalNotification,
            checkUnread: checkUnreadMessages,
            show: showCustomerServiceNotification,
            hide: hideNotification
        };
    </script>
    
    <!-- 添加动画效果 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
</div>
</html> 